/**
 * 
 */
package com.munoor.dalai.server.api;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import com.munoor.dalai.server.model.Company;
import com.munoor.dalai.server.model.EMFService;
import com.munoor.dalai.server.model.wrappers.WrappedCompany;
import com.munoor.dalai.server.model.wrappers.WrappedCompanyList;
import com.sun.jersey.api.NotFoundException;

/**
 * @author Osho Ilamah
 * @since version 1.0 (07 April 2011)
 */
@Path("/admin/companies")
public class AdminCompaniesService {
	@Context
	UriInfo uriInfo;
	@Context
	Request request;

	@POST
	@Consumes({ MediaType.APPLICATION_JSON })
	public Response createCompany(WrappedCompany postData) {
		EntityManager em = EMFService.get().createEntityManager();
		EntityTransaction txn = em.getTransaction();
		try {
			Company company = postData.unmarshall();
			txn.begin();
			em.persist(company);
			txn.commit();
			return Response.created(uriInfo.getAbsolutePathBuilder().path("" + company.getCompanyId()).build()).build();
		} catch (Exception e) {
			return Response.serverError().build();
		} finally {
			em.close();
		}
	}

	@SuppressWarnings("unchecked")
	@GET
	@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
	public WrappedCompanyList getCompanys(@QueryParam("start") @DefaultValue("0") int start, @QueryParam("items") @DefaultValue("10") int items) {
		EntityManager em = EMFService.get().createEntityManager();
		try {
			List<Company> companyObjects = em.createNamedQuery("Companies.findAll").setFirstResult(start).setMaxResults(items).getResultList();
			List<WrappedCompany> companyWrappers = new ArrayList<WrappedCompany>();
			for (Company c : companyObjects) {
				companyWrappers.add(new WrappedCompany(c));
			}
			int existingCount = ((Integer) em.createNamedQuery("Companies.getCompanyCount").getSingleResult()).intValue();

			int nextStart = existingCount > (start + items) ? (start + items) : 0;
			int prevStart = (start - items) > 0 ? (start - items) : 0;
			String next = "";
			if (nextStart > 0) {
				next = "start=" + nextStart + "&items=" + items;
			}
			WrappedCompanyList wrappedCompanysList = new WrappedCompanyList(companyWrappers, next, "start=" + prevStart + "&items=" + items, start, companyObjects.size(),
					existingCount);
			return wrappedCompanysList;
		} catch (Exception e) {
			throw new NotFoundException("Not Found");
		} finally {
			em.close();
		}
	}

	// SUB-RESOURCE CALLS
	// methods, etc to be handled by sub-resource

	@Path("{companyId}")
	// = /admin/companies/{companyId}
	public CompanyResource getCompany(@PathParam("companyId") Long companyId) {
		return new CompanyResource(uriInfo, request, companyId);
	}
}
